package com.woniu.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.rabbitmq.client.Channel;
import com.woniu.entity.FlowerInfo;
import com.woniu.entity.FlowerOrder;
import com.woniu.mapper.FlowerInfoMapper;
import com.woniu.mapper.FlowerOrderMapper;
import com.woniu.service.RabbitMQService;
import com.woniu.vo.OrderItemVoCZT;
import com.woniu.vo.OrderVoCZT;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@Service
public class RabbitMQServiceImpl implements RabbitMQService {
    @Resource
    private FlowerOrderMapper fom;
    @Resource
    private FlowerInfoMapper fim;

    @Resource
    private AlipayClient alipayClient;

    //死信队列监听器
    @Override
    @RabbitListener(queues = "死信队列")
    public void ttlOrder(Message message, Channel channel) throws IOException, AlipayApiException {
        //得到订单号
        String msg = new String(message.getBody());
        System.out.println("超时的订单：" + msg + "已被消费");
        //消费死信队列中的消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        FlowerOrder order = new FlowerOrder();
        order.setOrderId(Long.valueOf(msg));

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + Long.valueOf(msg) + "\"}");
        //请求
        AlipayTradeQueryResponse execute = alipayClient.execute(alipayRequest);
        String code = execute.getCode();
        Date sendPayDate = execute.getSendPayDate();
        if (!"10000".equals(code) || sendPayDate == null) {
            //修正订单内的鲜花售出数量及库存
            OrderVoCZT vo = fom.selectOrderByOrderId(msg);
            for (OrderItemVoCZT orderItem : vo.getOrderItems()) {
                int flowerId = orderItem.getFlowerId();
                FlowerInfo flowerInfo = fim.selectByPrimaryKey(flowerId);
                flowerInfo.setFlowerStoreCount(flowerInfo.getFlowerStoreCount() + orderItem.getBuyCount());
                flowerInfo.setFlowerSaleCount(flowerInfo.getFlowerSaleCount() - orderItem.getBuyCount());
                fim.updateByPrimaryKey(flowerInfo);
            }

            order.setStatus((byte) 0);
            order.setUpdateTime(new Date());
            fom.updateByPrimaryKeySelective(order);
        }
    }
}
